package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Notice;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.mapper.NoticeMapper;
import cn.wolfcode.qo.NoticeQueryObject;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.INoticeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.List;

@Service
public class NoticeServiceImpl implements INoticeService {

    @Autowired
    private NoticeMapper noticeMapper;
    @Autowired
    private EmployeeMapper employeeMapper;


    @Override
    public void updateStatus(Long noticeId , HttpSession session) {
        //修改公告为发布状态
        noticeMapper.updateStatus(noticeId);
        //往关系表未读取关系
        Employee employee = (Employee) session.getAttribute("USER_IN_SESSION");
        List<Employee> list = employeeMapper.selectAll();
        for (int i = 0; i < list.size(); i++) {
            if (employee.getId()==list.get(i).getId()){
                list.remove(i);
            }
        }
        for (Employee e:list){
            noticeMapper.empRead(e.getId(),noticeId);
        }
    }


    @Override
    public void save(Notice notice) {
        noticeMapper.insert(notice);
    }

    @Override
    public void delete(Long id) {
        noticeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(Notice notice) {
        noticeMapper.updateByPrimaryKey(notice);
    }

    @Override
    public Notice get(Long id) {
        return noticeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Notice> listAll() {
        return noticeMapper.selectAll();
    }

    @Override
    public PageInfo<Notice> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize()); //对下一句sql进行自动分页
        List<Notice> notices = noticeMapper.selectForList(qo); //里面不需要自己写limit
        return new PageInfo<Notice>(notices);
    }

    @Override
    public void updateEmpReadStatus(HttpSession session,Long noticeId) {
        Employee employee = (Employee) session.getAttribute("USER_IN_SESSION");
        noticeMapper.updateEmpReadStatus(employee.getId(),noticeId);
    }

    @Override
    public List<Notice> selectByNoReadNotice(NoticeQueryObject qo) {
        List<Notice> list = noticeMapper.selectByNoReadNotice(qo);
        return list;
    }
}
